package rapier.sso.server.handler.impl;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import rapier.sso.common.utils.SpringContextUtils;
import rapier.sso.core.config.redis.RedisClient;
import rapier.sso.core.entity.TDbSysUserEntity;
import rapier.sso.core.service.ITDbSysUserService;
import rapier.sso.server.constant.RapierServerConstant;
import rapier.sso.server.handler.IAppAuthHandler;
import rapier.sso.server.model.AppCredential;

@Component
public class SmsAppAuthHandler implements IAppAuthHandler {

	@Autowired
	private RedisClient redisClient;

	@Autowired
	private ITDbSysUserService userBaseService;

	@Override
	public boolean support(AppCredential credential) {
		if (credential.getLoginModel() == null) {
			return false;
		}
		return StringUtils.isNotBlank(credential.getLoginModel().getAccount())
				&& StringUtils.isNotBlank(credential.getLoginModel().getSmsKey());
	}

	@Override
	public boolean auth(AppCredential credential) {
		HttpServletRequest req = SpringContextUtils.getHttpServletRequest();
		String smsVal = credential.getLoginModel().getSmsVal();
		String smsKey = credential.getLoginModel().getSmsKey();
		Object redisSms = redisClient.get(RapierServerConstant.REDIS_SSO_USER_SMS_KEY + smsKey);
		// 判断验证码
		if (redisSms == null || !redisSms.toString().equals(smsVal.trim())) {
			credential.setError("验证码错误!");
			return false;
		}
		TDbSysUserEntity userEntity = null;
		String account = req.getParameter("account");
		if (credential.getUserEntity() == null) {// 不存在
			QueryWrapper<TDbSysUserEntity> query = new QueryWrapper<TDbSysUserEntity>();
			query.eq("user_account", account);
			query.last("limit 1");
			userEntity = userBaseService.getOne(query, false);
			if (userEntity == null) {
				credential.setError("用户不存在!");
				return false;
			}
			credential.setUserEntity(userEntity);
		}
		return true;
	}

	@Override
	public void release(AppCredential credential) {
		String smsKey = credential.getLoginModel().getSmsKey();
		redisClient.remove(RapierServerConstant.REDIS_SSO_USER_SMS_KEY + smsKey);
	}

}
